import { Menu } from "antd";
import React, { FC, useEffect } from "react";
import { menuOption, menus } from "./data";
import { Link, RouteComponentProps, withRouter } from "react-router-dom";
import "./index.scss";
const { SubMenu } = Menu;

const rootSubmenuKeys = [
  "dashbord",
  "customerManagement",
  "commodityCenter",
  "orderManagement",
  "priceManagement",
  "InventoryManagement",
  "rbacManagement",
];

const SideBar: FC<RouteComponentProps> = (props) => {
  const [openKeys, setOpenKeys] = React.useState([""]);
  const [selectedKeys, setSelectedKeys] = React.useState([""]);
  // const [collapsed, setCollapsed] = React.useState(false);
  // const onCollapse = () => {
  //   setCollapsed(!collapsed);
  // };

  useEffect(() => {
    let path =props.location.pathname.split('/')
    path = path.filter(item => item !== 'detail')
    if(path[path.length-1] === 'detail') {}
    setSelectedKeys([path[path.length-1]])
    setOpenKeys([path[path.length-2]])
    
  },[props.location.pathname]);

  const onOpenChange = (keys: any) => {
    const latestOpenKey = keys.find((key: any) => openKeys.indexOf(key) === -1);

    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };

  const onClick = (keys: any) => {
    setSelectedKeys([keys.key]);
  };

  const renderMenus = (data: menuOption[]) => {
    return data.map((item: menuOption) => {
      if (item.children && item.children.length > 0) {
        return (
          <SubMenu
            key={item.key}
            title={
              <span>
                <span>{item.name}</span>
              </span>
            }
          >
            {renderMenus(item.children)}
          </SubMenu>
        );
      } else if (item.children && item.children.length === 0) {
        return (
          <Menu.Item key={item.key}>
            <Link to={item.url}>{item.name}</Link>
          </Menu.Item>
        );
      } else {
        return (
          <Menu.Item key={item.key}>
            <Link to={item.url}>{item.name}</Link>
          </Menu.Item>
        );
      }
    });
  };

  return (
    <Menu
      style={{ width: "200px" }}
      mode="inline"
      openKeys={openKeys}
      onOpenChange={onOpenChange}
      selectedKeys={selectedKeys}
      onClick={onClick}
    >
      {renderMenus(menus)}
    </Menu>
  );
};

export default withRouter(SideBar);
